import React, { useEffect, useState } from 'react';
import { history} from 'umi'
import { Tabs,Button, Icon,List,Switch,Picker,Stepper, Toast } from 'antd-mobile'
import { getChapter,getAnswerRecord,genQuestionRecord } from '@/services/edu'
import { toChinesNum } from '@/utils/utils'
import Empty from '@/components/Empty';
import { storage,LOCALSTATE } from '@/utils';

import styles from './index.less'

function Chapter() {
  const { query = {} } = history.location as any;
  const { id } = query;
  const local = storage.get(LOCALSTATE,true)
  const [his,setHis] = useState([{},{}])
  const [isRandom,setRandom] = useState(false)
  const [num,setNum] = useState(5)
  const [errNum,setErr] = useState(0)
  const [rightNum,setRight] = useState(0)
  const [alreadyNum,setAlreadyNum] = useState(0)
  const [type,setType] = useState<any>([1])
  const [chapterInfo,setChapter] = useState<any>({})
  const [tabs,setTabs] = useState([])
  const [cursection,setsections] =useState<any>({})

  const fetchChapter = async()=>{
    if(id){
      const res = await getChapter({chapterId:id})
      if(res?.code===1){
        
        setChapter(res.response)
        document.title = res.response?.name;
        const sections:any =[{title: '全部',name:res.response?.name}];

        (res.response?.sectionList||[]).map((item,index)=>{
          
          sections.push({
            ...item,
            title:`第${toChinesNum(index+1)}节`,
          })
        })
        setTabs(sections)
        setsections({...res.response,isChapter:true})
        fetchAnswerRecord({chapterId:id})
      }
    }
  }
  const fetchAnswerRecord = async(param)=>{
    const subjectId =local.currentSubjectId
    const res = await getAnswerRecord({...param,subjectId})
    if(res?.code===1){
      setHis(res.response?.list||[])
    }
  }
  useEffect(()=>{
    fetchChapter()
    
  },[])
  
  const handleAnswer =async()=>{
    
    const params:any = {
      answerType:isRandom?1:0,
      subjectId:local.currentSubjectId,
      chapterId:id,
      chapterName:cursection.name,
      title:cursection.title,
      sectionId:cursection.isChapter?undefined:cursection.id,

    }
    if(isRandom){
      params.randomTotalCount=num
      params.excludCorrecCount=rightNum;
      params.excludWrongCount=errNum
      params.alreadyNum=alreadyNum
    }
    const res = await genQuestionRecord(params)
    if(res?.code===1&&res.response?.questionIds){
      storage.set('questionIds',res.response?.questionIds)
      history.push(`/answer?id=${res.response?.id}`)
    }else{
      Toast.fail(res.message||'生成题目失败')
    }

  }
  const handleTabChange =(v,index)=>{
    const params = v===0?{chapterId:v.id}:{sectionId:v.id}
    fetchAnswerRecord(params)
    setsections({...v,index,isChapter:index===0})

  }
  const handleMore = ()=>{
    // cursection.isChapter
    history.push(`/history/answer?chapterId=${cursection.isChapter?id:''}&sectionId=${cursection.id}`)
  }
  return (
    <div className={styles.chapter}>
      
      <Tabs tabs={tabs}
        initialPage={0} 
        renderTabBar={props => <Tabs.DefaultTabBar {...props} page={15} />}
        tabBarPosition="left"
        onChange={handleTabChange}
        tabDirection="vertical" >
      
      </Tabs>
      <div className={styles.setting}>
        <div className={styles.top}>{cursection.isChapter?chapterInfo.name:cursection.name}</div>
        <div className={styles.title}>历史答题数据 <Button onClick={()=>history.push(`/history/error?chapterId=${cursection.isChapter?id:''}&sectionId=${cursection.id}`)} type="primary" size="small">进入错题库</Button></div>
        <div className={styles.table}>
          <div className={styles.row}>
            <span>序号</span>
            <span>进展</span>
            <span>错题数</span>
            <span>正确率</span>
            <span>类型</span>
          </div>
          {his.length?<>{
            his.map((item:any,i)=>(i<4&&<div key={i} className={styles.row}>
              <span>{i+1}</span>
              <span>{item.recordOrder}/{item.recordSum}</span>
              <span>{item.questionError||'-'}题</span>
              <span>{item.correctPercent||'-'}%</span>
              <span>{item.answerType?'随机':'顺序'}</span>
            </div>))
          }
          <div className={styles.more} onClick={handleMore}>更多 <Icon type="right"/></div></>:<Empty/>}
          
        </div>
        <div className={styles.title}>做题方式 </div>
        <List>
          <List.Item
            extra={<Switch
              checked={isRandom}
              onChange={() => setRandom(!isRandom)}
            />}
          >随机</List.Item>
          
          
          {/* <Picker onChange={(v)=>setType(v)} value={type} data={[{label:'错题数',value:1},{label:'对题数',value:2},{label:'做题数',value:3}]} cols={1} className="forss">
            <List.Item arrow="horizontal">排除项</List.Item>
          </Picker>
          <List.Item
            wrap
            extra={
              <Stepper
                showNumber
                max={10}
                min={0}
                value={errNum}
                onChange={setErr}
              />}
          >
          数量
          </List.Item> */}
          {isRandom&&<>
            <List.Item
              wrap
              extra={
                <Stepper
                  // style={{ width: '100%', minWidth: '100px' }}
                  showNumber
                  max={100}
                  min={5}
                  step={5}
                  value={num}
                  onChange={setNum}
                />}
            >
            答题数量
            </List.Item>
            <List.Item
            wrap
            extra={
              <Stepper
                // style={{ width: '100%', minWidth: '100px' }}
                showNumber
                max={10}
                min={0}
                value={errNum}
                onChange={setErr}
              />}
          >
          排除错题数
          </List.Item>
          <List.Item
            wrap
            extra={
              <Stepper
                // style={{ width: '100%', minWidth: '100px' }}
                showNumber
                max={10}
                min={0}
                value={rightNum}
                onChange={setRight}
              />}
          >
          排除对题数
          </List.Item>
          <List.Item
            wrap
            extra={
              <Stepper
                // style={{ width: '100%', minWidth: '100px' }}
                showNumber
                max={10}
                min={0}
                value={alreadyNum}
                onChange={setAlreadyNum}
              />}
          >
          排除做题数
          </List.Item>
          </>}
          
        </List>

        <Button type="primary" onClick={handleAnswer}>开始答题</Button>
      </div>

    </div>
  );
}

export default Chapter;
